"""
  Created by Amor on 2018-08-27
"""
import json
import base64
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
# from urllib.parse import urlparse, parse_qs
# from VueShop.settings import ALI_PUB_KEY_PATH, PRIVATE_KEY_PATH

__author__ = '骆杨'


class AliPay(object):
    """
    支付宝支付接口
    """
    def __init__(self, **kwargs):
        self.app_id = kwargs['app_id']
        self.app_notify_url = kwargs['app_notify_url']
        self.app_private_key_path = kwargs['app_private_key_path']
        self.app_private_key = None
        self.return_url = kwargs['return_url']
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())

        self.alipay_public_key_path = kwargs['alipay_public_key_path']
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.import_key(fp.read())

        if kwargs['debug'] is True:
            self.__gateway = 'https://openapi.alipaydev.com/gateway.do'
        else:
            self.__gateway = 'https://openapi.alipay.com/gateway.do'

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            'subject': subject,
            'out_trade_no': out_trade_no,
            'total_amount': total_amount,
            'product_code': 'FAST_INSTANT_TRADE_PAY',
        }
        biz_content.update(kwargs)
        data = self.build_body('alipay.trade.page.pay', biz_content, return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            'app_id': self.app_id,
            'method': method,
            'charset': 'utf-8',
            'sign_type': 'RSA2',
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'version': '1.0',
            'biz_content': biz_content
        }

        if return_url is not None:
            data['notify_url'] = self.app_notify_url
            data['return_url'] = self.return_url

        return data

    def sign_data(self, data):
        data.pop('sign', None)
        unsigned_items = self.ordered_data(data)
        unsigned_string = '&'.join('{0}={1}'.format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode('utf-8'))
        quoted_string = '&'.join('{0}={1}'.format(k, quote_plus(v)) for k, v in unsigned_items)

        signed_string = quoted_string + '&sign=' + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)

        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        sign = base64.encodebytes(signature).decode('utf8').replace('\n', '')
        return sign

    def _verify(self, raw_content, signature):
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode('utf8'))
        if signer.verify(digest, base64.decodebytes(signature.encode('utf8'))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            data.pop("sign_type")
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)


if __name__ == '__main__':
    pass

    # return_url = ''
    # o = urlparse(return_url)
    # query = parse_qs(o.query)
    # processed_query = {}
    # ali_sign = query.pop("sign")[0]

    # alipay = AliPay(
    #     app_id='2016091700529381',
    #     app_notify_url='http://47.98.207.4:8080/alipay/return/',
    #     app_private_key_path=PRIVATE_KEY_PATH,
    #     alipay_public_key_path=ALI_PUB_KEY_PATH,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
    #     debug=True,  # 默认False,
    #     return_url='http://47.98.207.4:8080/alipay/return/'
    # )

    # for key, value in query.items():
    #     processed_query[key] = value[0]
    # print(alipay.verify(processed_query, ali_sign))

    # url = alipay.direct_pay(
    #     subject='测试订单',
    #     out_trade_no='20170202iid',
    #     total_amount=100,
    #     return_url='http://47.98.207.4:8080/alipay/return/'
    # )
    # re_url = 'https://openapi.alipaydev.com/gateway.do?{data}'.format(data=url)

    # print(re_url)
